package com.leetcode.deal.support;


/**
 * @Author: WuPeng
 * @Date: 2022/4/2 5:34 下午
 *
 * 移除链表元素
 *    用到了临时虚拟头结点，可以不用在对头结点删除的时候进行单独处理
 *
 */
public class RemoveLinkedElement_203 {

    public static ListNode removeElement(ListNode head, Integer target){
        //如果头结点为空，则直接返回null
        if (head == null)
            return null;

        //构建一个临时的虚拟节点，并将其next节点向head
        ListNode dummy = new ListNode(-1, head);
        ListNode prev  = dummy;
        ListNode curr  = head;

        while (curr != null){
            if (curr.value == target){
                prev.next = curr.next;
            } else {
                prev = curr;
            }
            curr = curr.next;
        }
        return dummy.next;
    }

    public static void main(String[] args) {
        ListNode head = ListNode.getLinkedList(10);
        System.out.print("原链表-->    ");
        ListNode.printLink(head);

        ListNode newHead = removeElement(head, 5);

        System.out.print("移除后链表--> ");
        ListNode.printLink(newHead);
    }

}
